package com.kinon.ogt.api.convert;

import android.support.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.kinon.ogt.model.BaseResponse;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/4/25
 */
public class GsonResponseConverter<T> implements Converter<ResponseBody, T> {

    private final Gson mGson;
    private TypeAdapter<T> mAdapter;
    private Type mType;

    GsonResponseConverter(Gson gson, TypeAdapter<T> adapter, Type type) {
        this.mGson = gson;
        this.mAdapter = adapter;
        this.mType = type;
    }

    @Override
    public T convert(@NonNull ResponseBody value) throws IOException {
        try {
            String responseBody = value.string();
            JSONObject json = new JSONObject(responseBody);

            boolean code = json.getBoolean("code");

            if (code) {
                return mGson.fromJson(responseBody, mType);
            } else {
                return (T) new BaseResponse<>(json.getBoolean("code"), json.getString("msg"), json.opt("data"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            value.close();
        }
        return null;
    }
}
